package com.ec50n9.server.auth

import cn.dev33.satoken.interceptor.SaRouteInterceptor
import cn.dev33.satoken.router.SaRouter
import cn.dev33.satoken.stp.StpUtil
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@Configuration
class SaTokenConfigure(private val corsInterceptor: CorsInterceptor) : WebMvcConfigurer {

    private val logger = LoggerFactory.getLogger(SaTokenConfigure::class.java)

    override fun addInterceptors(registry: InterceptorRegistry) {
        // 需要鉴权的 Path
        val addPathPatterns = listOf("/**")

        // 不需要鉴权的 Path，比如登录和注册接口就不需要鉴权
        val excludePathPatterns = listOf(
            "/api/auth/token",
            "/api/auth/register",
            "/api-docs",
            "/swagger-ui.html",
            "/swagger-ui/*",
            "/error",
            "/favicon.ico",
            "/api/files/download/*"
        )

        // 需要登录但不需要权限的 Path
        val needLoginPathPatterns = listOf(
            "/api/auth/logout",
            "/api/auth/self",
            "/api/files/upload*"
        )

        val interceptor = SaRouteInterceptor { req, _, _ ->
            logger.info("请求: ${req.method} ${req.requestPath}")
            // 账号自有资源，只需登录而不用权限
            SaRouter.match(req.requestPath in needLoginPathPatterns).check { _ ->
                StpUtil.checkLogin()
            }.stop()
            // 权限检查
            SaRouter.match(req.requestPath) { _ ->
                StpUtil.checkLogin()
                StpUtil.checkPermission("${req.method.lowercase()}===${req.requestPath}")
            }
        }

        registry.addInterceptor(corsInterceptor)
            .addPathPatterns("/**")

        registry.addInterceptor(interceptor)
            .addPathPatterns(addPathPatterns)
            .excludePathPatterns(excludePathPatterns)
    }
}
